package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.model.ListPartsRequest;
import com.aliyun.oss.model.PartSummary;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAAsyncClient;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.apache.commons.collections4.BagUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备管理Service业务层处理
 * 
 * @author lcl
 * @date 2025-05-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void getProductFromIot() {
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(RedisKeyConstants.IOT_ALL_PRODUCT_LIST, products);
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> getAllProduct() {
        List<ProductSummary> productSummaryList = (List<ProductSummary>) redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST);
        if (ObjectUtil.isEmpty(productSummaryList)){
            return List.of();
        }
        List<ProductVo> productVoList = BeanUtil.copyToList(productSummaryList, ProductVo.class);
        return productVoList;
    }

    /**
     * 注册设备
     */
    @Override
    public void logonProduct(DeviceDto dto) {
        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        String name = dto.getDeviceName();
        LambdaQueryWrapper<Device> deviceName = new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(name), Device::getDeviceName, name);
        if (deviceMapper.selectCount(deviceName) > 0) {
            throw new RuntimeException("设备名称重复");
        }

        //2.检验设备标识码nodeId是否重复
        String nodeId = dto.getNodeId();
        LambdaQueryWrapper<Device> deviceNodId = new LambdaQueryWrapper<Device>()
                .eq(StrUtil.isNotBlank(nodeId), Device::getNodeId, nodeId);
        if (deviceMapper.selectCount(deviceNodId) > 0) {
            throw new RuntimeException("设备标识码重复");
        }

        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品(产品唯一标识)
        LambdaQueryWrapper<Device> deviceLambdaQueryWrapper = new LambdaQueryWrapper<Device>()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType,dto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey());
        if (deviceMapper.selectCount(deviceLambdaQueryWrapper) > 0) {
            throw new RuntimeException("同一位置绑定了同一类产品");
        }

        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        //添加产品id，前端从radis里查
        body.withProductId(dto.getProductKey());
        //添加设备标识码,前端填写
        body.withNodeId(dto.getNodeId());
        //添加产品名称，前端填写
        body.withDeviceName(dto.getDeviceName());

        //设置密钥，运用UUID生成会带有“-”，需换为空字符串，否者会超出32位
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(key);
        //添加密钥
        body.withAuthInfo(authInfo);

        request.withBody(body);

        String iotId = "";
        try {
            AddDeviceResponse addDeviceResponse = client.addDevice(request);
            iotId = addDeviceResponse.getDeviceId();
        } catch (Exception e) {
            throw new RuntimeException("注册失败");
        }

        //5.设备数据保存到数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(key);
        device.setIotId(iotId);

        save(device);
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo selectProductDetail(String iotId) {
        //查询iot，得到设备状态，激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        String status = null;
        String activeTime = null;
        try {
            ShowDeviceResponse response = client.showDevice(request);
            status = response.getStatus();
            activeTime = response.getActiveTime();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("物联网接口 - 查询设备详情，调用失败");
        }

        //查询数据库
        Device device = getOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
        );

        //返回vo
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(status);

        if (StringUtil.isNotEmpty(activeTime)) {
            LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(time);
        }

        return vo;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);

        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);

            Object properties = response.getShadow().get(0).getReported().getProperties();
            JSONObject parse = JSONUtil.parseObj(properties);

            String time = response.getShadow().get(0).getReported().getEventTime();

            LocalDateTime localDateTime = LocalDateTimeUtil.parse(time, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = localDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            List list = new ArrayList<>();

            parse.forEach((key,value) -> {
                Map<String, Object> map = new HashMap<>();
                map.put("functionId",key);
                map.put("eventTime", eventTime);
                map.put("value", value);

                list.add(map);
            });

            return list;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("物联网接口 - 查询设备上报数据，调用失败");

        }
    }

    /**
     * 查询产品详情(报警规则模块使用)
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //参数校验
        if(StrUtil.isEmpty(productKey)){
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        List<ServiceCapability> serviceCapabilities;
        try {
            response = client.showProduct(showProductRequest);

            //判断是否存在服务数据
            serviceCapabilities = response.getServiceCapabilities();
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }

        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);

    }
}
